/*
 * @Author: xiaoyangzhao
 * @Date:   2018-03-31 19:57:33
 * @Last Modified by:   xiaoyangzhao
 * @Last Modified time: 2018-09-19 15:41:04
 */
// var _ticker = 0,
// 	testInter = setInterval(function() {

// 		(_ticker === 0) && console.time('canvas')
// 		_ticker++
// 		if (_ticker > (139 / 3) && !/#\/index/img.test(location.hash)) {
// 			// clearInterval(testInter)
// 			// console.timeEnd('canvas')
// 		}
// if (!!document.querySelector('canvas')) {
// 	clearInterval(testInter)

// import * as THREE from 'three'
import * as THREE from '../../../../static/three.module.min'
import Projects from '../../../../static/Projector'
import CanvasRenders from '../../../../static/CanvasRenderer'

const CUThree = function(THREE) {
  const SEPARATION = 100
  const AMOUNTX = 50
  const AMOUNTY = 50

  let container
  // let stats
  let camera
  let scene
  let renderer
  let particles
  let particle
  let count = 0
  let mouseX = 0
  let mouseY = 0

  let windowHalfX = window.innerWidth / 2
  let windowHalfY = window.innerHeight / 2

  init()
  // animate()

  function init() {
    container = document.createElement('div')
    container.setAttribute('v-once', '')
    container.className = 'canvas-container'
    document.body.appendChild(container)

    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000)
    camera.position.z = 1000
    camera.position.y = 300

    scene = new THREE.Scene()
    // scene.background = new THREE.Color(0x01011B)

    particles = []

    // const PI2 = Math.PI * 2
    // var material = new THREE.SpriteCanvasMaterial({
    const material = new THREE.SpriteMaterial({

      // color: 0x0099cc,
      // color: 0xffffff,
      // color: 0x3261ac,
      map: new THREE.CanvasTexture(generateSprite()),
      blending: THREE.AdditiveBlending
      // alpha:true,
      // antialias: true,
      // color: 0x0072e3,
      // program: function(context) {

      // 	// var gradient = context.createLinearGradient(0, 0, 0, canvas.height)
      // 	//          gradient.addColorStop(0, "#1e4877")
      // 	//          gradient.addColorStop(0.5, "#4584b4")
      // 	context.beginPath()
      // 	context.arc(0, 0, 0.5, 0, PI2, true)
      // 	// context.fillStyle = 'rgba(255, 255, 255, 0.7)'
      // 	// context.globalAlpha = 0.5
      // 	// context.fillStyle = gradient
      // 	context.fill()

      // }

    })
    material.transparent = true

    let i = 0

    for (let ix = 0; ix < AMOUNTX; ix++) {
      for (let iy = 0; iy < AMOUNTY; iy++) {
        particle = particles[i++] = new THREE.Sprite(material)
        particle.position.x = ix * SEPARATION - ((AMOUNTX * SEPARATION) / 2)
        particle.position.z = iy * SEPARATION - ((AMOUNTY * SEPARATION) / 2)
        scene.add(particle)
      }
    }

    // renderer = new THREE.CanvasRenderer()
    renderer = new THREE.WebGLRenderer({ alpha: true })
    renderer.setPixelRatio(window.devicePixelRatio)
    renderer.setSize(window.innerWidth, window.innerHeight)
    // renderer.setClearAlpha(1)
    // renderer.setClearColorHex( 0xffffff, 1)
    renderer.setClearColor(0x01011b, 0)
    container.appendChild(renderer.domElement)

    // stats = new Stats()
    // container.appendChild( stats.dom )

    document.addEventListener('mousemove', onDocumentMouseMove, false)
    document.addEventListener('touchstart', onDocumentTouchStart, false)
    document.addEventListener('touchmove', onDocumentTouchMove, false)

    window.addEventListener('resize', onWindowResize, false)
  }

  function generateSprite() {
    const canvas = document.createElement('canvas')
    canvas.width = 32
    canvas.height = 32

    const context = canvas.getContext('2d')
    const gradient = context.createRadialGradient(canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2)
    gradient.addColorStop(0, 'rgba(255,255,255,1)')
    gradient.addColorStop(0.2, 'rgba(0,255,255,1)')
    gradient.addColorStop(0.4, 'rgba(0,0,64,1)')
    gradient.addColorStop(1, 'rgba(0,0,0,1)')

    context.fillStyle = gradient
    context.fillRect(0, 0, canvas.width, canvas.height)

    return canvas
  }

  function onWindowResize() {
    windowHalfX = window.innerWidth / 2
    windowHalfY = window.innerHeight / 2

    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()

    renderer.setSize(window.innerWidth, window.innerHeight)
  }

  function onDocumentMouseMove(event) {
    mouseX = event.clientX - windowHalfX
    mouseY = event.clientY - windowHalfY - 350
  }

  function onDocumentTouchStart(event) {
    if (event.touches.length === 1) {
      event.preventDefault()
      mouseX = event.touches[0].pageX - windowHalfX
      mouseY = event.touches[0].pageY - windowHalfY
    }
  }

  function onDocumentTouchMove(event) {
    if (event.touches.length === 1) {
      event.preventDefault()
      mouseX = event.touches[0].pageX - windowHalfX
      mouseY = event.touches[0].pageY - windowHalfY
    }
  }

  /* function animate() {
		setTimeout(animate, 50)
		render()
		(Date.now() % 10 === 0) && render()
		requestAnimationFrame(animate)
		stats.update()
	} */
  const inter = setInterval(render, 80)
  let step = 0

  function render() {
    step++
    if (step % 20 === 0 && location.hash !== '#/index') {
      // console.log(location.hash, inter)
      clearInterval(inter)
      document.querySelector('.canvas-container') && document.body.removeChild(document.querySelector('.canvas-container'))
      // document.querySelector('.anim-mask').style.display = 'none'
    }
    camera.position.x += (mouseX - camera.position.x) * 0.05
    camera.position.y += (-mouseY - camera.position.y) * 0.05
    camera.position.y = camera.position.y < 200 ? 200 : camera.position.y
    camera.lookAt(scene.position)

    let i = 0
    for (let ix = 0; ix < AMOUNTX; ix++) {
      for (let iy = 0; iy < AMOUNTY; iy++) {
        particle = particles[i++]
        particle.position.y = (Math.sin((ix + count) * 0.3) * 50) +
					(Math.sin((iy + count) * 0.5) * 50)
        particle.scale.x = particle.scale.y = (Math.sin((ix + count) * 0.3) + 1) * 10 +
					(Math.sin((iy + count) * 0.5) + 1) * 10
        // particle.scale.x = particle.scale.y = Math.random() * 32 + 16
      }
    }

    renderer.render(scene, camera)
    count += 0.1
  }
}

const execThree = function() {
  !document.querySelector('.canvas-container') && Projects(THREE, function(THREE) {
    CanvasRenders(THREE, function(THREE) {
      CUThree(THREE)
    })
  })
}

export default execThree
// 		console.timeEnd('canvas')
// 	}
// }, 1390)
